const tools = require('../tools/tool');
/**
 * 
 * @param {*} pool 
 * @param {*} openId 
 * 根据在哪公众号的OpenId,查询到在哪小程序用户用户身份信息
 */
exports.queryUserInfo = async (pool, openId) => {
    const sql = 'select user.pa_user_id,user.public_id,pguser.idcard_num from (select c.pa_user_id,c.public_id,c.union_id from wx_pg_contact c where c.public_id = ? and c.update_time = (select max(update_time) from wx_pg_contact c where c.public_id = ?)) user,wx_pg_user pguser where user.pa_user_id = pguser.id and pguser.logout = 1';
    const result = await pool.query(sql, [openId, openId]);
    if (result.length) {
        return tools.toTuoFeng(result[0]);
    }
    return null;
}

/**
 * 查询活动配置信息
 * @param {c} pool 
 * @param {*} activeId 
 */
exports.h5activeConfig = async (pool, activeId = 1) => {
    const sql = 'select * from h5_activity_config where id =?';
    const result = await pool.query(sql, [activeId]);
    if (result.length) {
        return tools.toTuoFeng(result[0]);
    }
    return null;
}

/**
 * @param {查询参与活动的合同模板}} idCardNum 
 */
exports.getContractMouldIdByIdCardNum = async (pool, idCardNum, activeCouldMouldId) => {
    const sql = 'select contract_mould_id, create_time from ais_contract where signer_credentials_no = ? and contract_mould_id = ? order by create_time desc limit 0,1';
    const result = await pool.query(sql, [idCardNum, activeCouldMouldId]);
    if (result.length) {
        return tools.toTuoFeng(result[0]);
    }
    return null;
}

//批量给没有发红包的用户使用
exports.queryDateStrRedEnvByStatusNewUserActive = async (pool, status, dataStr) => {
    const sqls = `select *  from h5_red_record where status = ? and date_str = ? and active_type = 'newUserActive' limit 0,28`;
    const result = await pool.query(sqls, [status, dataStr]);
    if (result.length) {
        return tools.toTuoFeng(result);
    }
    return [];
}

/**
 * 更新活动数量
 * @param {*} pool 
 * @param {*} activeId 
 * @param {*} count 
 */
exports.updateH5activeConfig = async (pool, activeId = 1, count) => {
    const sql = 'update h5_activity_config set active_count_limit = active_count_limit - ?  where id =? and active_count_limit > 0';
    const result = await pool.query(sql, [count, activeId]);
    return result.affectedRows > 0;
}

//新用户转发红包限制
//查询当天是否记录过红包情况，
exports.hasNewUserDateRedEnvlopRecord = async (pool, idcardNum, dataStr, activeType, contractMouldId) => {
    console.log('hasDateRedEnvlopRecord', idcardNum, dataStr, activeType, contractMouldId);
    const sqls = ` select *  from h5_red_record where idcard_num = ? and date_str = ? and active_type = ? and contract_mould_id = ?`;
    const result = await pool.query(sqls, [idcardNum, dataStr, activeType, contractMouldId]);
    if (result.length) {
        return tools.toTuoFeng(result[0]);
    }
    return null;
}